Skip to content

test: add unit tests for sortServicePortStatus and sortServiceLoadBalancerIngress#7710

Open
Goutham-Annem wants to merge 1 commit into
karmada-io:masterfrom
Goutham-Annem:test/7657-sort-service-helpers
Open

test: add unit tests for sortServicePortStatus and sortServiceLoadBalancerIngress#7710
Goutham-Annem wants to merge 1 commit into
karmada-io:masterfrom
Goutham-Annem:test/7657-sort-service-helpers

Conversation

@Goutham-Annem

Copy link
Copy Markdown

What type of PR is this?

/kind test

What this PR does / why we need it

Adds unit tests for two unexported helper functions in pkg/util/helper/service.go:

  • sortServicePortStatus — sorts []corev1.PortStatus by port number, then protocol, then nil error before non-nil, then by error string value
  • sortServiceLoadBalancerIngress — sorts []corev1.LoadBalancerIngress by non-empty hostname before empty, then hostname alphabetically, then IP, then non-nil IPMode before nil, then by IPMode value

Each test case uses the for range 1000 loop pattern (matching the existing TestDedupeAndSortServiceLoadBalancerIngress style) to eliminate any sort-algorithm randomness.

Which issue(s) this PR fixes

Fixes #7657

Does this PR introduce a user-facing change?

No

Signed-off-by: Goutham Annem gouthemannem@gmail.com

…ancerIngress

Adds TestSortServicePortStatus and TestSortServiceLoadBalancerIngress
covering all sort keys: port/protocol/error ordering for PortStatus,
and hostname/IP/IPMode ordering for LoadBalancerIngress.

Signed-off-by: Goutham Annem <gouthemannem@gmail.com>
Copilot AI review requested due to automatic review settings July 5, 2026 16:29
@karmada-bot

Copy link
Copy Markdown
Contributor

@Goutham-Annem: The label(s) kind/test cannot be applied, because the repository doesn't have them.

Details

In response to this:

What type of PR is this?

/kind test

What this PR does / why we need it

Adds unit tests for two unexported helper functions in pkg/util/helper/service.go:

  • sortServicePortStatus — sorts []corev1.PortStatus by port number, then protocol, then nil error before non-nil, then by error string value
  • sortServiceLoadBalancerIngress — sorts []corev1.LoadBalancerIngress by non-empty hostname before empty, then hostname alphabetically, then IP, then non-nil IPMode before nil, then by IPMode value

Each test case uses the for range 1000 loop pattern (matching the existing TestDedupeAndSortServiceLoadBalancerIngress style) to eliminate any sort-algorithm randomness.

Which issue(s) this PR fixes

Fixes #7657

Does this PR introduce a user-facing change?

No

Signed-off-by: Goutham Annem gouthemannem@gmail.com

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@karmada-bot

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign xishanyongye-chang for approval. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request improves the test coverage for internal service helper functions. By introducing unit tests for sorting logic related to service port statuses and load balancer ingresses, the changes ensure that these components behave consistently and correctly under various input conditions, fixing issue #7657.

Highlights

  • Unit Test Coverage: Added comprehensive unit tests for the unexported helper functions sortServicePortStatus and sortServiceLoadBalancerIngress in pkg/util/helper/service.go.
  • Test Methodology: Implemented a loop-based testing pattern (running 1000 iterations) to ensure deterministic sorting behavior and eliminate potential randomness in the sort algorithms.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@karmada-bot karmada-bot added the size/L Denotes a PR that changes 100-499 lines, ignoring generated files. label Jul 5, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces unit tests, specifically TestSortServicePortStatus and TestSortServiceLoadBalancerIngress, to verify the sorting of service port statuses and load balancer ingresses. The review feedback correctly identifies a flaw in the test implementation: because the sorting functions operate in-place, the 1000-iteration loops designed to eliminate randomness only sort an unsorted slice in the first iteration, while the remaining 999 iterations run on already-sorted data. To ensure robust and deterministic testing, the tests should be updated to copy the slices before sorting them in each iteration.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +235 to +241
for range 1000 { // eliminate randomness in sorting
sortServicePortStatus(tt.ports)
pass := assert.Equalf(t, tt.want, tt.ports, "sortServicePortStatus(%v)", tt.ports)
if !pass {
break
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The for range 1000 loop is intended to eliminate randomness and ensure deterministic sorting. However, because sortServicePortStatus sorts the slice in-place, tt.ports is sorted in the very first iteration. In the remaining 999 iterations, the function is called on an already-sorted slice, which defeats the purpose of the loop.

To properly test determinism, you should create a fresh copy of the slice in each iteration. Note that the underlying sortServicePortStatus function currently violates strict weak ordering when both elements have a nil Error field (returning true in both directions), which makes deterministic testing even more critical.

			for range 1000 {
				ports := make([]corev1.PortStatus, len(tt.ports))
				copy(ports, tt.ports)
				sortServicePortStatus(ports)
				pass := assert.Equalf(t, tt.want, ports, "sortServicePortStatus(%v)", tt.ports)
				if !pass {
					break
				}
			}

Comment on lines +314 to +320
for range 1000 { // eliminate randomness in sorting
sortServiceLoadBalancerIngress(tt.ingresses)
pass := assert.Equalf(t, tt.want, tt.ingresses, "sortServiceLoadBalancerIngress(%v)", tt.ingresses)
if !pass {
break
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Similar to TestSortServicePortStatus, sortServiceLoadBalancerIngress sorts the slice in-place. As a result, tt.ingresses is sorted in the first iteration, and the subsequent 999 iterations run on an already-sorted slice.

To ensure the test actually verifies determinism across multiple runs, create a copy of the slice inside the loop. Note that the underlying sortServiceLoadBalancerIngress function currently violates strict weak ordering when both elements have a nil IPMode field (returning true in both directions), which makes deterministic testing even more critical.

			for range 1000 {
				ingresses := make([]corev1.LoadBalancerIngress, len(tt.ingresses))
				copy(ingresses, tt.ingresses)
				sortServiceLoadBalancerIngress(ingresses)
				pass := assert.Equalf(t, tt.want, ingresses, "sortServiceLoadBalancerIngress(%v)", tt.ingresses)
				if !pass {
					break
				}
			}

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds new unit tests in the helper utilities test suite to validate the sorting semantics of sortServicePortStatus and sortServiceLoadBalancerIngress in pkg/util/helper/service.go, improving confidence in these non-trivial ordering rules.

Changes:

  • Add TestSortServicePortStatus covering port number, protocol, nil-vs-non-nil error, and error-string ordering.
  • Add TestSortServiceLoadBalancerIngress covering hostname-vs-IP priority, hostname ordering, IP ordering, and IPMode nil/value ordering.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +233 to +243
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
for range 1000 { // eliminate randomness in sorting
sortServicePortStatus(tt.ports)
pass := assert.Equalf(t, tt.want, tt.ports, "sortServicePortStatus(%v)", tt.ports)
if !pass {
break
}
}
})
}
Comment on lines +312 to +322
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
for range 1000 { // eliminate randomness in sorting
sortServiceLoadBalancerIngress(tt.ingresses)
pass := assert.Equalf(t, tt.want, tt.ingresses, "sortServiceLoadBalancerIngress(%v)", tt.ingresses)
if !pass {
break
}
}
})
}
Comment on lines +210 to +215
{
name: "same port and protocol, nil error sorts first",
ports: []corev1.PortStatus{
{Port: 80, Protocol: "TCP", Error: new("some-error")},
{Port: 80, Protocol: "TCP"},
},
@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 42.08%. Comparing base (56d5d87) to head (e72fb78).
⚠️ Report is 16 commits behind head on master.
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #7710      +/-   ##
==========================================
+ Coverage   42.06%   42.08%   +0.01%     
==========================================
  Files         879      879              
  Lines       54831    54831              
==========================================
+ Hits        23063    23073      +10     
+ Misses      30023    30017       -6     
+ Partials     1745     1741       -4     
Flag Coverage Δ
unittests 42.08% <ø> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/L Denotes a PR that changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

test: add unit tests for sortServicePortStatus and sortServiceLoadBalancerIngress

4 participants